package javaer.starter.util;

/**
 * @author yangzhen
 * @date 2021/12/31 15:54
 * @since 1.0.0
 */
public class JavaNamedUtil {

    /**
     * 对单独的className进行校验
     *
     * @param className
     * @return
     */
    private static boolean isValidJavaIdentifier(String className) {
        //确定是否允许将指定字符作为 Java 标识符中的首字符。
        if (className.length() == 0
                || !Character.isJavaIdentifierStart(className.charAt(0)))
            return false;

        String name = className.substring(1);
        for (int i = 0; i < name.length(); i++)
            //确定指定字符是否可以是 Java 标识符中首字符以外的部分。
            if (!Character.isJavaIdentifierPart(name.charAt(i)))
                return false;

        return true;
    }

    /**
     * 对 package name 和 class name 进行校验
     *
     * @param fullName
     * @return
     */
    public static boolean isValidJavaFullClassName(String fullName) {
        if (fullName.equals("")) {
            return false;
        }
        boolean flag = true;
        try {
            if (!fullName.endsWith(".")) {
                int index = fullName.indexOf(".");
                if (index != -1) {
                    String[] str = fullName.split("\\.");
                    for (String name : str) {
                        if (name.equals("")) {
                            flag = false;
                            break;
                        } else if (!isValidJavaIdentifier(name)) {
                            flag = false;
                            break;
                        }
                    }
                } else if (!isValidJavaIdentifier(fullName)) {
                    flag = false;
                }

            } else {
                flag = false;
            }

        } catch (Exception ex) {
            flag = false;
        }
        return flag;
    }

    public static void main(String[] args) {
        System.out.println(JavaNamedUtil.isValidJavaFullClassName("com.sdf."));
        System.out.println(JavaNamedUtil.isValidJavaFullClassName("com.sdf"));
        System.out.println(JavaNamedUtil.isValidJavaFullClassName("com.sdf.1"));
        System.out.println(JavaNamedUtil.isValidJavaFullClassName("com.sdf.1c"));
        System.out.println(JavaNamedUtil.isValidJavaFullClassName("1.com.sdf"));
        System.out.println(JavaNamedUtil.isValidJavaFullClassName("1c.com.sdf"));
        System.out.println(JavaNamedUtil.isValidJavaFullClassName("com.1.sdf"));
        System.out.println(JavaNamedUtil.isValidJavaFullClassName("com.c1.sdf"));
    }
}
